<?php

namespace App\Http\Controllers\Api\Wap;

use App\Http\Controllers\Common\ApiController;
use App\Models\Setting\SysSetting;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LoginController extends ApiController {

    /**
     * 手机端微信登录
     * @param Request $request
     * @Date 2022/11/20 23:37
     * @Author Rudy
     * @return \Illuminate\Http\JsonResponse
     */
    public function wxLogin(Request $request) {
        try{

            $this->validate($request, ['code'=>'required']);

            $code = $request->input('code');
            $pid = $request->input('pid');
            $app_id = config('wechat.default')['app_id'];
            $secret = config('wechat.default')['secret'];
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$app_id&secret=$secret&code=$code&grant_type=authorization_code";
            $res = json_decode(makeRequest($url)['result'],true);
            $access_token = $res['access_token'];
            $open_id = $res['openid'];
            $union_id = $res['unionid'];

            $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$open_id&lang=zh_CN";
            $userInfo = json_decode(makeRequest($url)['result'],true);

            $nick_name = $userInfo['nickname']??'';
            $sex = $userInfo['sex']??0;
            $avatar = $userInfo['headimgurl']??'';

            $info = [
                'open_id'=>$open_id,
                'nick_name'=>$nick_name,
                'avatar'=>$avatar,
                'union_id'=>$union_id
            ];


            $user = User::where('union_id',$union_id)->first();
            //当是新创建用户的时候
            if(empty($user)){
                if(!empty($pid)){
                    $pUser =  User::where('union_id',$pid)->first();
                    if(!empty($pUser)) $info['parent_id'] = $pUser->id;
                }
                $user = User::create($info);
            }else{
                $user = User::where(compact('union_id'))->update($info);
            }

            //Log::info('wap',compact('pid'));

            //根据unionid查找父亲

            //Log::info('wap',$info);

            $user = User::firstOrCreate(compact('union_id'),$info);
            $user->token = createNewToken($user->id,'wap');
            //Log::info('wxLogin',$user->toArray());

            $mapMemberType = SysSetting::whereIn('key',['first','month','quarter','year'])->pluck('item_desc','key')->toArray();
            if($user->is_member==1){
                $type = $user->type;
                //$type = $user->getMemberType()->type??'';
                $user->member_type = $type;
                $user->member_type_name = $mapMemberType[$type]??'普通用户';
            }else{
                $user->member_type = 0;
                $user->member_type_name = '普通用户';
            }


            /*DB::table('login_log')->insert([
                'user_id'=>$user->id,
                'last_login_time'=>date('Y-m-d H:i:s'),
                'device'=>'wap'
            ]);*/

            return responseSuccess($user->toArray());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }
}
